import { Component } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { IonicPage, NavController, NavParams ,ToastController} from 'ionic-angular';
import { Data } from './data';
import 'rxjs/add/operator/toPromise';
import { Https } from '../../app/http.service'
import { Observable } from "rxjs/Observable";

import { HomePage } from '../home/home';  

import { App } from '../../app/app.component'; 
/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
    selector: 'page-login',
    templateUrl: 'login.html',
})
export class LoginPage {
	// ajaxUrl = new Config().Url
	massTime : number = 59;
	cli:Boolean = false
	PhoneUrl = new Https().Url +"act=auto_register_login&op=get_sms_appcaptchas"
	LoginUrl = new Https().Url +"act=connect&op=check_auto_appcode"
	aplyUrl: string = new Https().Url + "act=goods&op=app_get_user_info";
	clear: Boolean = false;
	Datas: Data[];
	user:string;
	capt : string;
	constructor(public navCtrl: NavController, public navParams: NavParams, public toastCtrl: ToastController, private http: HttpClient) {
    }

    ionViewDidLoad() {
		console.log('ionViewDidLoad LoginPage');
	}
	BackWin(){
		this.navCtrl.setRoot(App);
	}
	Back(){
		this.navCtrl.pop();
	}
	//验证手机号，发送验证码
	sendMass(user: string){
		this.user = user;
		let userCheck = /^1(3|4|5|7|8)\d{9}$/.test(user);
		if (user != "" && user.length == 11 && userCheck == true){
			this.sendCapt(0)
			// let toast = this.toastCtrl.create({
			// 	message: '验证码已发送',
			// 	duration: 1000
			// });
			// toast.present();
			this.massTime = 59;
			var then = this;
			let cap = setInterval(function(){
				if (then.massTime!=0){
					then.massTime--;
					console.log(then.massTime);
				}else{
					clearInterval(cap);
					then.cli = false;
					
				}
				
			},1000)
			this.cli = true;
			console.log(user)
		} else {
			this.alertPop('手机号输入有误！')
		}
		console.log(userCheck);
	}
	//发送验证码卑服务器
	userLogin(user: string,pwd:string){
		if (this.user == null){
			this.alertPop('请获取验证码')
		}else{
			let pwdCheck = /\d{6}/.test(pwd);
			let userCheck = /^1(3|4|5|7|8)\d{9}$/.test(user);
			if (pwdCheck != false && userCheck != false ){
				this.capt = pwd;
				this.sendCapt(1)

				
			}else{
				this.alertPop('手机号或验证码输入有误！')
			}
			console.log(pwdCheck);
			console.log(userCheck);	
		}
		
	}
	textClear(value:string,type:number){
		if(type == 0){
			if (value.length == 0) {
				this.clear = false;
			} else {
				this.clear = true;
			}
		}else{
			value =null;
		}
		
	}
	
	sendCapt(num) {
		//num :1 验证码 //num：0 手机号
		let thin = this
		if(num == 0){
			fetch(this.PhoneUrl, {
				method: 'post',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				body:"phone="+this.user,
			}).then(function (response) {
				response.text().then(function(res){
					if(res != ''){
						let data = JSON.parse(res).Code;
						if (data == '0'){
							thin.alertPop('验证码发送成功')
						}else{
							thin.alertPop('验证码发送失败')
						}
					}else{
						thin.alertPop('验证码发送成功')
					}
					
				})
				
			}).catch(function (err) {
				// 出错了;等价于 then 的第二个参数,但这样更好用更直观 :(
				this.alertPop('验证码发送失败')
			});
		}else if(num == 1){
			let thin = this
			fetch(this.LoginUrl, {
				method: 'post',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				body: "phone=" + this.user + "&auth_code=" + this.capt,
			}).then(function (response) {
				response.text().then(function (res) {
					console.log(JSON.parse(res))
					if (JSON.parse(res).token != null && JSON.parse(res).mid != null){
						localStorage.setItem("token", JSON.parse(res).token);
						localStorage.setItem("mid", JSON.parse(res).mid);
						localStorage.setItem("loginState", "0");
						thin.alertPop('登陆成功')
						fetch(thin.aplyUrl, {
							method: 'post',
							headers: {
								'Content-Type': 'application/x-www-form-urlencoded'
							},
							body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token"),
						}).then((response) => {
							response.text().then((con) => {
								let user = JSON.parse(con);
								localStorage.setItem("userName", user['user_name'])
								localStorage.setItem("userPic", user['user_pic'])
								thin.Back()
								// console.log(123)
								// location.reload()
							}).catch((err) => {
								let toast = thin.toastCtrl.create({
									message: '登陆出错，请联系客服',
									duration: 1000
								}); toast.present();
							})

						}).catch((err) => {
							thin.alertPop('登陆失败，请重试')
						})
						
					}else{
						thin.alertPop('登陆失败，请重试')
					}
				})

			}).catch(function (err) {
				console.log(err)
			});
		}
		
		
	}
	userUpdate() {
		

		if (localStorage.getItem("token") != null && localStorage.getItem("mid") != null && localStorage.getItem("loginState") == '0') {
			fetch(this.aplyUrl, {
				method: 'post',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
			    body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token"),
			}).then((response) => {
			    response.text().then((con) => {
					let user = JSON.parse(con);
					localStorage.setItem("userName", user['user_name'])
					localStorage.setItem("userPic", user['user_pic'])
					//检测用户交易密码 0为空1为不空
					localStorage.setItem("payPwd", user['member_paypwd'])
			    }).catch((err) => {
					let toast = this.toastCtrl.create({
						message: '登陆失败，请联系客服' + err,
						duration: 1000
					}); toast.present();
			    })

			}).catch((err) => {
				let toast = this.toastCtrl.create({
					message: '登陆失败，请联系客服' + err,
					duration: 1000
				}); toast.present();
			})
		} else {
			// localStorage.setItem("userName", "请登陆")
			// localStorage.setItem("userPic", "./assets/imgs/user.png")
		}

		console.log(this);

	}
	
	alertPop(err){
		let toast = this.toastCtrl.create({
			message: err,
			duration: 1000
		}); toast.present();
	}
}
